package config

import (
	"encoding/json"
	"github.com/nacos-group/nacos-sdk-go/v2/clients"
	"github.com/nacos-group/nacos-sdk-go/v2/common/constant"
	"github.com/nacos-group/nacos-sdk-go/v2/vo"
	"github.com/spf13/viper"
	"log"
)

type ApiConfig struct {
	Mysql Mysql `mapstructure:"mysql" json:"mysql"`
	Redis Redis `mapstructure:"redis" json:"redis"`
}
type Nacos struct {
	IpAddr      string `mapstructure:"ipAddr" json:"ipAddr"`
	Port        int64  `mapstructure:"port" json:"port"`
	DataId      string `mapstructure:"dataId" json:"dataId"`
	NameSpaceId string `mapstructure:"nameSpaceId" json:"nameSpaceId"`
	Group       string `mapstructure:"group" json:"group"`
}
type Mysql struct {
	User     string `mapstructure:"user" json:"user"`
	Password string `mapstructure:"password" json:"password"`
	Host     string `mapstructure:"host" json:"host"`
	Port     int    `mapstructure:"port" json:"port"`
	Database string `mapstructure:"database" json:"database"`
}
type Redis struct {
	Addr     string `mapstructure:"addr" json:"addr"`
	Password string `mapstructure:"password" json:"password"`
	DB       int    `mapstructure:"DB" json:"DB"`
}

var (
	GlobalConfig ApiConfig
	NacosConfig  Nacos
)

func ConfigInit(shopYaml string) Nacos {
	v := viper.New()
	v.SetConfigFile(shopYaml)
	err := v.ReadInConfig()
	if err != nil {
		log.Printf("配置读取错误:%v", err)
	}
	nacosconfig := Nacos{}
	err = v.Unmarshal(&nacosconfig)
	if err != nil {
		log.Printf("配置解析错误:%v", err)
	}
	NacosConfig = nacosconfig
	return NacosConfig
}
func NacosInit(nameSpaceId string, ipAddr string, port int64, dataId string, group string) ApiConfig {
	clientConfig := constant.ClientConfig{
		NamespaceId:         nameSpaceId,
		TimeoutMs:           5000,
		NotLoadCacheAtStart: true,
		LogDir:              "/tmp/nacos/log",
		CacheDir:            "/tmp/nacos/cache",
		LogLevel:            "debug",
	}
	serverConfigs := []constant.ServerConfig{
		{
			IpAddr:      ipAddr,
			ContextPath: "/nacos",
			Port:        uint64(port),
			Scheme:      "http",
		},
	}
	client, _ := clients.CreateConfigClient(map[string]interface{}{
		"serverConfigs": serverConfigs,
		"clientConfig":  clientConfig,
	})
	content, err := client.GetConfig(vo.ConfigParam{
		DataId: dataId,
		Group:  group})
	if err != nil {
		log.Printf("获取配置出错：%v", err)
	}
	globalconfig := ApiConfig{}
	err = json.Unmarshal([]byte(content), &globalconfig)
	if err != nil {
		log.Printf("解析全局配置错误:%v", err)
	}
	GlobalConfig = globalconfig
	return GlobalConfig
}
